﻿using Microsoft.IdentityModel.Tokens;
using Model;
using Model.Enums;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Utils.AppHelper;

namespace Api.Jwt
{
    public static class JWTHelper
    {
        /// <summary>
        /// 创建token
        /// </summary>
        /// <param name="claims"></param>
        /// <param name="JwtTime"></param>
        /// <returns></returns>
        public static string CreateToken(Claim[] claims, string JwtTime)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppHelper.GetJsonValue("JWT:SecurityKey")));
            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: AppHelper.GetJsonValue("JWT:Issuer"),
                audience: AppHelper.GetJsonValue("JWT:Audience"),
                claims: claims,
                expires: DateTime.Now.AddHours(Convert.ToInt16(JwtTime)),
                signingCredentials: cred
            );

            var jwt = new JwtSecurityTokenHandler().WriteToken(token);
            return jwt;
        }

        /// <summary>
        /// 设置登录的参数
        /// </summary>
        /// <param name="users"></param>
        /// <param name="detail"></param>
        /// <returns></returns>
        public static Claim[] SetLoginDic(Users users, UsersDetail detail)
        {
            var claims = new[]
            {
                new Claim(ResultEnums.LOGIN.RYID,users.UserName),
                new Claim(ResultEnums.LOGIN.RYXM, users.Email),
            };
            return claims;
        }

    }
}
